import request from "./request.js"
import {sleep} from "./util.js"
import store from '../store/index.js';

// 获取用户信息
export const getUserInfo = () => {
	request.post('merchant/userInfo').then(res=>{
		store.commit('setUserInfo', res);
	})
} 
			
// 登录
export const login =  async () =>  {
	 return new Promise(async (resolve, reject) => {
		 // 正在登录中，就等待登录结果，防止重复登录
		 if(store.state.is_logining == true){
		 	// 重复尝试5秒后，提示
		 	for(i=0; i<=100; i++){
		 		await sleep(50);
		 		if(store.state.is_logining == false) break;
		 		if(i==100){
		 			uni.showToast({
		 				title: '网络不佳，请稍后重试',
		 				duration: 5000
		 			});
		 			reject(new Error('登录超时'));
					return;
		 		}
		 	}
		 }
		// 如果已登录就直接返回
		if (store.state.hasLogin) {
		   resolve(true);
		   return;
		 }
		 
		 store.commit('is_logining', true);
		 
		 // 获取本地 token 判断是否过期
		 let token = uni.getStorageSync('token');
		 let timeout = uni.getStorageSync('timeout');
		 let timestamp = Math.floor(Date.now() / 1000);
		 if(token && timestamp<timeout-200) {
		 	console.log('token：' + token)
		 	store.commit('login');
		 	store.commit('is_logining', false);
			resolve(true);
			return;
		}
		 	
		// #ifdef MP-WEIXIN
		wx.login({
			success(res) {
				if (res.code) {
					console.log('code：' + res.code)
					request.post('merchant/login', {
						code: res.code
					}).then(res=>{
						uni.setStorageSync('token', res.token);
						uni.setStorageSync('timeout', res.timeout);
						// 请求获取用户信息
						store.commit('login');
						store.commit('is_logining', false);
						resolve(true);
					})
				} else {
					console.log('获取code失败！' + res.errMsg)
					store.commit('is_logining', false);
					reject(err);
				}
			},
			fail(err) {
				console.log('wx.login:fail' + err)
				store.commit('is_logining', false);
				reject(err);
			}
		})
		// #endif
	 });
}